package com.cencat.framework.file.controller;

import com.cencat.common.model.Result;
import com.cencat.framework.file.dto.FileUploadRequest;
import com.cencat.framework.file.service.FileStorageService;
import com.cencat.framework.file.vo.FileInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * 文件存储控制器
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor
public class FileStorageController {
    
    private final FileStorageService fileStorageService;
    
    /**
     * 上传单个文件
     */
    @PostMapping("/upload")
    public Result<FileInfoVO> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "storageType", defaultValue = "LOCAL") String storageType,
            @RequestParam(value = "storagePath", required = false) String storagePath,
            @RequestParam(value = "businessModule", required = false) String businessModule,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam(value = "accessLevel", defaultValue = "1") Integer accessLevel,
            @RequestParam(value = "isTemporary", defaultValue = "false") Boolean isTemporary) {
        
        FileUploadRequest request = new FileUploadRequest();
        request.setFile(file);
        request.setStorageType(storageType);
        request.setStoragePath(storagePath);
        request.setBusinessModule(businessModule);
        request.setBusinessId(businessId);
        request.setAccessLevel(accessLevel);
        request.setIsTemporary(isTemporary);
        
        FileInfoVO fileInfo = fileStorageService.uploadFile(request);
        return Result.success(fileInfo);
    }
    
    /**
     * 批量上传文件
     */
    @PostMapping("/upload/batch")
    public Result<List<FileInfoVO>> uploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "storageType", defaultValue = "LOCAL") String storageType,
            @RequestParam(value = "storagePath", required = false) String storagePath,
            @RequestParam(value = "businessModule", required = false) String businessModule,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam(value = "accessLevel", defaultValue = "1") Integer accessLevel,
            @RequestParam(value = "isTemporary", defaultValue = "false") Boolean isTemporary) {
        
        List<FileUploadRequest> requests = Arrays.stream(files)
                .map(file -> {
                    FileUploadRequest request = new FileUploadRequest();
                    request.setFile(file);
                    request.setStorageType(storageType);
                    request.setStoragePath(storagePath);
                    request.setBusinessModule(businessModule);
                    request.setBusinessId(businessId);
                    request.setAccessLevel(accessLevel);
                    request.setIsTemporary(isTemporary);
                    return request;
                })
                .toList();
        
        List<FileInfoVO> fileInfos = fileStorageService.uploadFiles(requests);
        return Result.success(fileInfos);
    }
    
    /**
     * 下载文件
     */
    @GetMapping("/download/{fileKey}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileKey) {
        byte[] fileContent = fileStorageService.downloadFile(fileKey);
        FileInfoVO fileInfo = fileStorageService.getFileInfo(fileKey);
        
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, 
                        "attachment; filename=\"" + fileInfo.getFileName() + "\"")
                .body(fileContent);
    }
    
    /**
     * 获取文件预览URL
     */
    @GetMapping("/preview/{fileKey}")
    public Result<String> getPreviewUrl(@PathVariable String fileKey) {
        String previewUrl = fileStorageService.getPreviewUrl(fileKey);
        return Result.success(previewUrl);
    }
    
    /**
     * 获取文件信息
     */
    @GetMapping("/info/{fileKey}")
    public Result<FileInfoVO> getFileInfo(@PathVariable String fileKey) {
        FileInfoVO fileInfo = fileStorageService.getFileInfo(fileKey);
        return Result.success(fileInfo);
    }
    
    /**
     * 删除文件
     */
    @DeleteMapping("/{fileKey}")
    public Result<Boolean> deleteFile(@PathVariable String fileKey) {
        boolean result = fileStorageService.deleteFile(fileKey);
        return Result.success(result);
    }
    
    /**
     * 批量删除文件
     */
    @DeleteMapping("/batch")
    public Result<Boolean> deleteFiles(@RequestBody List<String> fileKeys) {
        boolean result = fileStorageService.deleteFiles(fileKeys);
        return Result.success(result);
    }
    
    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists/{fileKey}")
    public Result<Boolean> fileExists(@PathVariable String fileKey) {
        boolean exists = fileStorageService.fileExists(fileKey);
        return Result.success(exists);
    }
    
    /**
     * 生成上传签名
     */
    @GetMapping("/signature")
    public Result<String> generateUploadSignature(
            @RequestParam String fileName,
            @RequestParam long fileSize) {
        String signature = fileStorageService.generateUploadSignature(fileName, fileSize);
        return Result.success(signature);
    }
    
    /**
     * 清理临时文件
     */
    @PostMapping("/cleanup/temporary")
    public Result<Integer> cleanupTemporaryFiles() {
        int count = fileStorageService.cleanupTemporaryFiles();
        return Result.success(count);
    }
}